package com.example.myapplication.coroutines

import com.example.myapplication.navigation.fragment.BaseLifeFragment
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.myapplication.R
import com.example.myapplication.databinding.FragmentCoroutinesLayoutBinding
import com.example.myapplication.utils.NameCreator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Created by xiaolong on 2022/4/19 9:09 下午
 * email：xinxiaolong123@foxmail.com
 */
open class CoroutinesFragment : BaseLifeFragment() {


    private var binding: FragmentCoroutinesLayoutBinding? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_coroutines_layout, container, false)
        binding = FragmentCoroutinesLayoutBinding.bind(view)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
    }

    override fun initLogHead(): String {
        return NameCreator.getInstance().getName("***********************CoroutinesFragment", hashCode())
    }



    private fun initData() {

        GlobalScope.launch {
            Dispatchers.Main
            logWithThread("================start================")
            val result= withContext(Dispatchers.IO){
                logWithThread("in io start")
                Thread.sleep(2000);
                logWithThread("in io end")
            }

            logWithThread("result="+result)

            logWithThread("================end================")

        }
    }

     fun logWithThread(text:String){
        Log.e("CoroutinesFragment",Thread.currentThread().name.plus("  "+text))
    }

}
